<?php
namespace App\Http\Controllers\Backstage;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Validator\UserVali;
use App\Model\Account\Administration;
use App\Model\Backstage\CustomerFollowSourde;
use App\Model\Backstage\Customers;
use App\Model\Backstage\RoomInfo;
use App\Model\Backstage\User;
use App\Model\Common\Position;
use App\Tool\Error;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;

/**
 * Class UserController
 * @package App\Http\Controllers\Backstage
 * 用户控制器
 * date:2018-4-30
 * author:lxy
 */
class UserController extends Controller
{
    protected $user;

    public function __construct()
    {
       $this->user = new User();
    }

    public function user()
    {
        $user = Auth::user();
        dd($user);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 获取中介公司员工列表
     */
    public function getUserList (Request $request)
    {
        $map['user.is_del'] = 0;
        $map['u_b_id'] = Auth::user()->u_b_id;//公司ID
        //部门ID
        $u_d_id = $request->input('u_d_id');
        $u_id = $request->input('u_id');
        if (!$u_d_id && !$u_id) {
            $map[] = ['u_d_id', '=', Auth::user()->u_d_id];
            $map[] = ['u_id', '=', Auth::user()->u_id];
        }
        if ($u_d_id){
            $map[] = ['u_d_id', '=', $u_d_id];
        }
        //员工Id
        if ($u_id){
            $map[] = ['u_id', '=', $u_id];
        }
        //员工名字
        $u_username = $request->input('u_username');
        if ($u_username){
            $map[] = ['u_username', 'like', "%".trim($u_username)."%"];
        }
        //员工账号
        $u_account_number = $request->input('u_account_number');
        if ($u_account_number){
            $map[] = ['u_account_number', 'like', "%".trim($u_account_number)."%"];
        }
        $list = $this->user->getUserList($map, env('PAGE_LIMIT_ADMIN'));
        if(!$list){
            return $this->error(Error::NULL_DATA);
        }
        return $this->success('ok',$list);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 添加中介公司员工账号信息
     */
    public function addUser (Request $request)
    {
        $params = $request->except('token');
        $vali = UserVali::validate($params);
        if(!$vali){
            return $this->error(Error::PARAM_MISSING);
        }
        $user_info = Auth::user();
        $params['u_b_id'] = $user_info->u_b_id;//公司
        $data = Administration::whetherAddNum($params['u_b_id']);//查看该中介公司当前还能不能新增员工
        if ($data) {
            return $this->error(Error::NUM_ACHIECE, '添加失败！公司最多创建人员数量：'.$data['num'].'人。现有'.$data['b_num'].'个');
        }
        $params['sId'] = $user_info->u_d_id;
        $params['uId'] = $user_info->u_id;
        $res = $this->user->addUser($params);
        if ($res === -1) {
            return $this->error(Error::REPEAT_PHONE);
        }
        if($res){
            return $this->success('ok', $res);
        }else{
            return $this->error(Error::ADD_ERROR);
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 修改中介公司员工信息
     */
    public function saveUser (Request $request)
    {
        $params = $request->except(['token','u_account_number']);
        $vali = UserVali::saveValidate($params);
        if(!$vali){
            return $this->error(Error::PARAM_MISSING);
        }
        $params['store_id'] = Auth::user()->u_d_id;//部门
        $params['uid'] = Auth::user()->u_id;//员工
        $res = $this->user->saveUser($params);
        if($res){
            return $this->success('ok','修改成功！');
        }else{
            return $this->error(Error::EDIT_ERROR);
        }
    }

    //服务后台删除图片(修改删除)
    public function delImage(Request $request){
        $params = $request->all();
        if(!$request->input('file_name')){
            return $this->error(Error::PARAM_MISSING);
        }
        $rel = User::delImage($params['file_name'], $params['uid']);
        if($rel){
            return $this->success('ok', '删除成功');
        }
        return $this->error(Error::EDIT_ERROR);
    }
    //添加删除七牛照片
//        public function delQiniuImg(Request $request){
//            $fileName = $request->input('file_name');
//            if(!$fileName){
//                return $this->error(Error::PARAM_MISSING);
//            }
//            $administration = new administration();
//            $rel = $administration->delqiniuimg($fileName);
//            if($rel){
//                return $this->success('ok', '删除成功');
//            }
//            return $this->error(Error::EDIT_ERROR);
//        }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 软删除中介公司员工信息
     */
    public function delUser(Request $request)
    {
        $uid = $request->input('u_id');
        if(!$uid){
            return $this->error(Error::PARAM_MISSING);
        }
        $thisUser = Auth::user()->u_id;
        $thisUserDepartment = Auth::user()->u_d_id;
        $res = $this->user->delUser($uid,$thisUser,$thisUserDepartment);
        if($res === -1){
            return $this->error(Error::OPERATION_ERROR);
        }
        if($res){
            return $this->success('ok','操作成功！');
        }else{
            return $this->error(Error::DEL_ERROR);
        }

    }

    //硬删除
    public function DeletePermanently(Request $request){
        $uid = $request->input('u_id');
        if(!$uid){
            return $this->error(Error::PARAM_MISSING);
        }
        $thisUser = Auth::user()->u_id;
        $thisUserDepartment = Auth::user()->u_d_id;
        $res = $this->user->DeletePermanently($uid,$thisUser,$thisUserDepartment);
        if($res === -1){
            return $this->error(Error::OPERATION_ERROR);
        }
        if($res){
            return $this->success('ok','操作成功！');
        }else{
            return $this->error(Error::DEL_ERROR);
        }
    }

    /*
     * 回收站用户列表
     */
    public function RecycleBinUserList(Request $request,User $user)
    {
        $param = $request->all();

        $where[] = ['u.u_b_id', Auth::user()->u_b_id];
        $where[] = ['u.is_del', 1];
        if($request->input('start_time')){
            $where[] = ['u.updated_at', '>=', strtotime($param['start_time'].' 00:00:00')];
        } else {
            $where[] = ['u.updated_at', '>=', strtotime(date('Y-m-d',strtotime('-3 month')).' 00:00:00')];
        }

        if($request->input('end_time')){
            $where[] = ['u.updated_at', '<=', strtotime($param['end_time'].' 23:59:59')];
        } else {
            $where[] = ['u.updated_at', '<=', time()];
        }

        //关键词智能搜索
        $keywords = '';
        if ($request->input('keywords')){
            //员工姓名
            $keywords = trim($request->input('keywords'));

        }
        $list =$user->recycleBinList(env('PAGE_LIMIT_ADMIN'),$where,$keywords);
         if (!$list) {
            $data['start'] = date('Y-m-d',strtotime('-3 month'));
            $data['end']  = date('Y-m-d',time());
            return $this->error(Error::NULL_DATA,$data);
        }

        $start = date('Y-m-d',strtotime('-3 month'));
        $end = date('Y-m-d',time());
        return $this->success('ok', $list,$start,$end);
    }

    /**上级重置员工密码为初始密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPassword(Request $request)
    {
        $uid = $request->input('u_id');
        if(!$uid){
            return $this->error(Error::PARAM_MISSING);
        }
        $res = User::resetPassword($uid);
        if (!$res) {
            return $this->error(Error::RESET_PASSWORD);
        }
        return  $this->success('ok', '重置密码成功新密码为（123456）');
    }

    /**修改密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updatePassword(Request $request)
    {
        $params = $request->all();
        $vali = UserVali::updatePassword($params);
        if(!$vali){
            return $this->error(Error::PARAM_MISSING);
        }
        if ($params['new_password'] !== $params['again_password']) {
            return $this->error(Error::TWO_PASSWORD_ERROR);
        }
        $res = User::updatePassword($params['new_password']);
        if (!$res) {
            return $this->error(Error::UPDATE_PASSWORD_FAIL);
        }
        return $this->success('ok', '修改成功！');

    }


    /**
     * 业务提醒
     */
    public function BusinessReminder()
    {

        $sourde = new CustomerFollowSourde();
        $data = $sourde->BusinessReminder();//业务提醒
        if (!$data) {
            return $this->error(Error::BUSINESS_REMIND);
        }
        $customerModel = new Customers();
        $roomModel = new RoomInfo();
        foreach($data as $key=>$value){

            if($value['type'] == 2){
                //客源
                $data[$key]['c_info'] =  $customerModel->getCustomersDetail($value['id']);
            }else if($value['type'] == 1){
                //房源
                $data[$key]['r_info'] = $roomModel->getRoomDetail($value['id']);


            }
        }
        return $this->success('ok', $data);
    }

    //业务处理
    public function BusinessProcessing(Request $request){
        $params = $request->all();
        $vali = UserVali::updateFollow($params);
        if(!$vali){
            return $this->error(Error::PARAM_MISSING);
        }
        $roomModel = new RoomInfo();
        $res = $roomModel->BusinessProcessing($params);
        if($res){
            return $this->success('ok', '处理成功');
        }

    }

    //房客跟进Id获取跟进与提醒
    public function getRoomCustomersRemind(Request $request){
        $params = $request->all();
        if($params['type'] == 1){
            //房源提醒    查    看房客源的信息
            $roomModel = new RoomInfo();
            $data = $roomModel->getRoomFollows($params['id']);
        }elseif($params['type'] == 2){
            //客源提醒    查   看房房源的信息
            $customerModel = new Customers();
            $data =  $customerModel->getCustomersFollows($params['id']);
        }
        return $this->success('ok', $data);
    }

    /**
     * 修改员工的权限
     */
    public function editUserPermission(Request $request)
    {
        $params = $request->all();
        $vali = UserVali::updatePermission($params);
        if(!$vali){
            return $this->error(Error::PARAM_MISSING);
        }
        $id = User::editUserPermission($params);
        if (!$id) {
            return $this->error(Error::UPDATE_PASSWORD_FAIL);
        }
        return $this->success('ok', '修改成功！');
    }

    /**
     * 添加员工之前获取职务的下拉框
     */
    public function getPositionList()
    {
        $id = Auth::user()['u_b_id'];
        $data = Position::downPosition($id);
        return $this->success('ok', $data);
    }
}